package net.zoneland.knowledge.aop;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.zoneland.knowledge.constant.Constants;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

public class AuthorityInterceptor implements AsyncHandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(AuthorityInterceptor.class);

    @Value("${app_token}")
    private String uniToken;

    static final String METHOD_GETUSERBYTIME = "/ua/getUserByTime";
    static final String METHOD_GETORGBYTIME = "/ua/getOrgByTime";

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        final String path = request.getServletPath();
        switch (path) {
            case METHOD_GETUSERBYTIME:
            case METHOD_GETORGBYTIME:
                final String token = request.getHeader(Constants.APP_TOKEN);
                if (StringUtils.isBlank(token) || !this.uniToken.equals(token)) {
                    return errorPrint(request, response);
                }
                break;
            default:
                return true;
        }
        return true;
    }

    private boolean errorPrint(HttpServletRequest request, HttpServletResponse response) {
        String referer = request.getHeader("referer");
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        log.error("No token information in the request header, access is denied! Request referer: {}, requestURI: {}, method: {}", new Object[] { referer, requestURI, method });
        response.setStatus(401);
        return false;
    }
}
